/*
 * MODULE  NAME  :
 * PROGRAM NAME  : tkapp.h
 * AUTHOR        : hotmocha(hotmocha@126.com)
 * CREATE  DATE  : 2015-10-21 15:04:46
 * PROGRAM DESC  :
 *
 * HISTORY       :
 *
 */
#ifndef _H_TKAPP_H_
#define _H_TKAPP_H_

#include "constants.h"
#include "list.h"
#include "clientinfo.dsc.h"
#include "tkevent.h"

struct tk_handler_param {
        event_handler handler;
        int handlerType;        /* 1:r 2:w 4:rw */
        void* data;
};

struct tk_file {
	char path_file_name[FILEPATHMAXLEN];
	int file_size;
	int cur_offset;		/* current send or recv bytes */
	FILE *file;
};

struct tk_message {
	int header_left_len;		/* shoud received or sent head len */ 
	char header[HEADERLEN + 1];
	int message_type;

	int body_len;
	int body_left_len;	/* should send or recv body len */
	char body[MAXMESSAGELEN + 1];
};


#define TK_CONNECT_SYNC_CLIENT_INFO		0
#define TK_CONNECT_SYNC_CLIENTS_LIST		1
#define TK_CONNECT_SYNC_CLIENTS_LIST_COMPLETE	2
#define TK_CONNECT_COMMUNICATING		3

struct tk_connect {
	clientinfo client;
	int stage;

	struct custom_socket *csock;
	struct tk_message send_msg[MAXMESSAGENUM];
	int msg_start;	/* to send */
	int msg_end; 	/* to recv */
	
	struct tk_message recv_msg;
	struct tk_file recv_file;
	struct tk_handler_param handlerParam;
/*
	int merrno;
        int finished:1;
        int failed:1;
*/
        int recving_head:1;
        int recving_body:1;
        int sending_head:1;
        int sending_body:1;

	struct list_head list_node;	/* insert into server_env clients_list */
};

/***
@RETURN:
        1. TK_AGAIN
        2. TK_ERROR(errno)
        3. TK_DONE(no use)
        4. TK_OK
        5. TK_NO_MORE_SEND_MSG
***/
int tk_do_send(struct custom_socket *s);

/*
@RETURN:
        1. TK_OK
        2. TK_AGAIN
        3. TK_ERROR
        4. TK_DONE      (remote close)
	5. TK_RECV_BODY_DONE
*/
int tk_do_recv(struct custom_socket *s);

/**
@RETURN
        1. TK_NEED_ADD_W_EVENT
        2. TK_OK
**/
int tk_do_add_send_msg(struct custom_socket *s, struct tk_message *send_msg);

int init_tk_message(struct tk_message *msg, char *body, int body_len, int type);
int set_tk_message_header(struct tk_message *msg, int body_len, int type);


struct tk_connect* get_tk_connect(struct custom_socket *s);
#endif
